
var seckill = {
		
		URL:{
			now:function(){
				return '/secKill/time/now';
			},
			exposer: function(secKillId){
				return '/secKill/' + secKillId + '/exposer';
			},
			execSecKill: function(secKillId, md5){
				return '/secKill/'+secKillId+'/'+md5+'/execSecKill';
			}
		},
		validatePhone: function(phone){
			if(phone && phone.length==11 &&!isNaN(phone)){
				return true;
			}
			return false;
		},
		
		validateResSucc: function(result) {
			if(result && result['status'] == 2){
				return true;
			}
			return false;
		},
		countDown: function(secKillId, nowTime, startTime, endTime) {
			var secKil_box = $('#secKill-box');
			
			if(nowTime > endTime){
				secKil_box.html('秒杀结束!');
			}else if(nowTime < startTime){
				secKil_box.countdown({
					until: (startTime - nowTime)/1000 + 1,
					format: 'DHMS',
					onExpiry: function(){
						seckill.handerSecKill(secKillId,secKil_box);
					}
				});
			}else{
				seckill.handerSecKill(secKillId,secKil_box);
			}
		},
		handerSecKill: function(secKillId, node) {
			node.hide().html('<button  class="btn btn-primary btn-lg" id="killBtn">开始秒杀</button>');
			$.post(seckill.URL.exposer(secKillId),{}, function(result) {
				if(seckill.validateResSucc(result)){
					var exporter = result['data'];
					if(exporter['exposed']){
						$('#killBtn').one('click', function(){
							$(this).addClass('disable');
							$.post(seckill.URL.execSecKill(secKillId, exporter['md5']),{}, function(result){
								if(seckill.validateResSucc(result)){
									node.html('<span class="label label-success">秒杀成功！<span>');
								}else{
									node.html('<span class="label label-danger">'+result['errMsg']+'<span>');
								}
							});
						});
					}else{
						seckill.countDown(secKillId, exporter['now'], exporter['start'], exporter['end']);
					}
				}else{
					console.log(result);
				}
			});
			node.show();
		},
		
		detail:{
			init: function(params) {
				var killPhone = $.cookie('phoneNum');
				var seckillId = params['seckillId'];
				var startTime = params['startTime'];
				var endTime = params['endTime'];
				
				if(!seckill.validatePhone(killPhone)){
					var killPhoneModal =  $('#killPhoneModal');
					killPhoneModal.modal( {
						show:true,
						backdrop:'static',
						keyboard:false
					});
					
					$('#killPhoneBtn').click(function(){
						var inputPhone = $('#killPhoneKey').val();
						//console.log('inputPhone:'+inputPhone)
						if(seckill.validatePhone(inputPhone)){
							$.cookie('phoneNum',inputPhone,{expires:7,path:'/secKill'});
							window.location.reload();
						}else{
							$('#killPhoneMessage').hide().html('<label class="label label-danger">输入的手机号格式不对！</label>').show(300);
						}
					});
				}
				
				$.get(seckill.URL.now(),{}, function(result){
					if(seckill.validateResSucc(result)){
						var now = result['data'];
						seckill.countDown(seckillId, now, startTime, endTime);
					}else{
						console.log('result:'+result);
					}
				});
			}
		}
		
}